import router from '@/router'
import { useUserStoreHook } from '@/store/modules/user'
import { usePermissionStoreHook } from '@/store/modules/permission'
import { ElMessage } from 'element-plus'
import { setRouteChange } from '@/hooks/useRouteListener'
import { useTitle } from '@/hooks/useTitle'
import { getToken } from '@/utils/local-storage'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const { setTitle } = useTitle()
NProgress.configure({ showSpinner: false })

// router.beforeEach(async (to, _from, next) => {
//   NProgress.start()
//   const userStore = useUserStoreHook()
//   const permissionStore = usePermissionStoreHook()
//   const token = getToken()
//   if (!token) {
//     if (to.meta?.licenseFree) {
//       return next()
//     }
//     return next('/login')
//   }

//   if (to.path === '/login') {
//     return next({ path: '/' })
//   }
//   if (userStore.roles.length !== 0) return next()

//   try {
//     await userStore.getInfo()
//     const roles = userStore.roles
//     permissionStore.setRoutes(roles)
//     permissionStore.addRoutes.forEach(route => router.addRoute(route))
//     next({ ...to, replace: true })
//   } catch (err) {
//     userStore.resetToken()
//     ElMessage.error(err.message || 'Router Has Error')
//     next('/login')
//   }
// })

router.beforeEach(async (to, _from, next) => {
  NProgress.start()

  const token = getToken()
  const permissionStore = usePermissionStoreHook()
  if (!token) {
    if (to.meta?.licenseFree) {
      return next()
    }
    return next('/login')
  }
  if (to.path === '/login') {
    return next({ path: '/' })
  }
    permissionStore.setRoutes()
    permissionStore.addRoutes.forEach(route => router.addRoute(route))
  next()
})

router.afterEach(to => {
  setRouteChange(to)
  setTitle(to.meta.title)
  NProgress.done()
})
